#!/bin/bash
watcher=/usr/local/emhttp/plugins/dynamix.file.integrity/scripts/watcher
conf=/etc/inotifywait.conf

watcher.start() {
  if [[ -z $(pgrep -f $watcher) ]]; then
    source $conf 2>/dev/null
    for disk in $(ls --indicator-style=none /mnt|grep -P '^disk[0-9]+'); do
      echo "start watching $disk"
      $watcher "$cmd" "$method" "$exclude" "$disk"
    done
  else
    echo "watcher already running!"
  fi
}

watcher.stop() {
  if [[ -n $(pgrep -f $watcher) ]]; then
    kill $(ps -ef|awk '/inotifywait.*disk[0-9]+$/ {print $2}')
    pkill -f $watcher
    for timer in {1..9}; do
      [[ -z $(pgrep -f $watcher) ]] && break
      sleep 1
    done
    [[ $timer -lt 9 ]] && echo "watcher stopped" || echo "watcher did not stop"
  else
    echo "watcher not running!"
  fi
  for disk in $(ls --indicator-style=none /mnt|grep -P '^disk[0-9]+'); do
    rm -f /var/run/hash.pipe.$disk
  done
}

watcher.restart() {
  watcher.stop
  sleep 1
  watcher.start
}

case "$1" in
'start'  ) watcher.start ;;
'stop'   ) watcher.stop ;;
'restart') watcher.restart ;;
        *) echo "Usage: $(basename $0) start|stop|restart"
esac
